package com.example.audiostreaming.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.example.audiostreaming.Bean.UserBean;
import com.example.audiostreaming.Bean.UserDataBean;
import com.example.audiostreaming.R;
import com.example.audiostreaming.base.BaseActivity;
import com.example.audiostreaming.base.BaseApplication;
import com.example.audiostreaming.implement.SubscriptionPresenter;
import com.example.audiostreaming.utils.UtilConstants;
import com.example.audiostreaming.utils.UtilUser;
import com.example.audiostreaming.views.InputView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.album.Announcer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";

    private InputView mInputPhone, mInputPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    private void initView() {
        initNavBar(false,"登录");
        mInputPhone=findViewById(R.id.input_phone);
        mInputPassword=findViewById(R.id.input_password);
    }

    /**
     * 注册
     * @param view
     */
    public void onRegisterClick(View view) {
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);
    }

    /**
     * 登录
     * @param view
     */
    public void onCommitCLick(View view) throws InterruptedException {
        String phone = mInputPhone.getInputStr();
        String password = mInputPassword.getInputStr();

        if (!UtilUser.validateLogin(this, phone, password)) {
            return;
        }

        getUserData(phone);

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    private void getUserData(String phone) throws InterruptedException {
        String mUrl = "http://192.168.0.107:8080/AndioStreamingService_war_exploded/";
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=GBK"), phone);
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(mUrl + "getUserData").post(requestBody).build();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure ==> "+e.getMessage());
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                String name = response.body().string();
//                UserBean.getUserBean().setName(name);
//                SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(UtilConstants.SP_NAME_USER, Context.MODE_PRIVATE);
//                SharedPreferences.Editor edit = sp.edit();
//                edit.putString(UtilConstants.SP_KEY_NAME, name);
//                edit.commit();
//                Log.d(TAG, "onResponse: "+name);
                String string = response.body().string();
//                Log.d(TAG, "onResponse: \n "+string);
                JsonParser jsonParser = new JsonParser();
                JsonArray jsonArray = jsonParser.parse(string).getAsJsonArray();
                Gson gson = new Gson();
                ArrayList<UserDataBean> userDataBeanArrayList = new ArrayList<>();
                for (JsonElement jsonElement : jsonArray) {
                    UserDataBean userDataBean = gson.fromJson(jsonElement, UserDataBean.class);
                    userDataBeanArrayList.add(userDataBean);
                }
                Log.d(TAG, "onResponse: "+userDataBeanArrayList.toString());
                for (UserDataBean userDataBean : userDataBeanArrayList) {
                    String name = userDataBean.getName();
                    UserBean.getUserBean().setName(name);
                    SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(UtilConstants.SP_NAME_USER, Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString(UtilConstants.SP_KEY_NAME, name);
                    edit.commit();


                    Album album = new Album();
                    album.setId(userDataBean.getId());
                    album.setAlbumTitle(userDataBean.getAlbumTitle());
                    album.setCoverUrlLarge(userDataBean.getCoverUrlLarge());
                    album.setAlbumIntro(userDataBean.getAlbumIntro());
                    album.setIncludeTrackCount(userDataBean.getIncludeTrackCount());
                    album.setPlayCount(userDataBean.getPlayCount());
                    Announcer announcer = new Announcer();
                    announcer.setNickname(userDataBean.getNickname());
                    album.setAnnouncer(announcer);

                    SubscriptionPresenter instance = SubscriptionPresenter.getInstance();
                    instance.addSubscription(album,false);
                }

            }
        });
        Thread.sleep(500);//解决回调方法过慢
    }
}
